package org.example.contestb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import org.example.contestb.Mapper.*;
import org.example.contestb.config.WebSocketServer;
import org.example.contestb.entity.MapData;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class MapTaskManager {

    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
    private final Map<String, ScheduledFuture<?>> taskMap = new ConcurrentHashMap<>();
    private final Gson gson = new Gson();

    @Autowired
    private MapDataMapper mapDataMapper;

    /**
     * 启动定时获取数据的任务
     * @param sessionId WebSocket会话ID
     * @param tableName 表名
     */
    public void startTask(String sessionId, String tableName) {
        // 如果已有任务，先取消
        stopTask(sessionId);
        
        log.info("=== 启动定时任务 === 会话ID: {}, 表名: {}", sessionId, tableName);
        
        // 检查WebSocket连接状态
        boolean isConnected = WebSocketServer.isConnected(sessionId);
        log.info("=== WebSocket连接状态 === 会话ID: {}, 已连接: {}", sessionId, isConnected);
        
        if (!isConnected) {
            log.warn("=== WebSocket未连接 === 会话ID: {}, 无法启动任务", sessionId);
            return;
        }
        
        // 启动前发送一条测试消息
        try {
            String startMessage = "{\"type\":\"taskStarted\",\"message\":\"开始获取" + tableName + "的数据\"}";
            WebSocketServer.sendMessage(sessionId, startMessage);
            log.info("=== 任务启动消息已发送 ===");
        } catch (Exception e) {
            log.error("=== 发送启动消息失败 ===", e);
        }

        Runnable task = new Runnable() {
            private int currentId = 1;

            @Override
            public void run() {
                // 每次执行前检查WebSocket连接状态
                if (!WebSocketServer.isConnected(sessionId)) {
                    log.warn("=== WebSocket已断开 === 会话ID: {}, 停止任务", sessionId);
                    stopTask(sessionId);
                    return;
                }
                
                try {
                    MapData data = mapDataMapper.getById(tableName, currentId);
                    if (data != null) {
                        String json = gson.toJson(data);
                        log.info("=== 获取到数据 === ID: {}, 数据: {}", currentId, json);
                        WebSocketServer.sendMessage(sessionId, json);
                        currentId++;
                    } else {
                        log.warn("=== 未找到数据 === ID: {}, 可能已到达数据末尾", currentId);
                        WebSocketServer.sendMessage(sessionId, 
                            "{\"type\":\"endOfData\",\"message\":\"已到达数据末尾\"}");
                    }
                } catch (Exception e) {
                    log.error("=== 数据处理异常 ===", e);
                    try {
                        WebSocketServer.sendMessage(sessionId, 
                            "{\"type\":\"error\",\"message\":\"数据获取异常: " + e.getMessage() + "\"}");
                    } catch (Exception ex) {
                        log.error("=== 发送错误通知失败 ===", ex);
                    }
                }
            }
        };

        // 首次延迟1秒执行，然后每3秒执行一次
        ScheduledFuture<?> future = executor.scheduleAtFixedRate(task, 1, 3, TimeUnit.SECONDS);
        taskMap.put(sessionId, future);
        log.info("=== 定时任务已启动 === 会话ID: {}", sessionId);
    }

    /**
     * 停止任务
     * @param sessionId WebSocket会话ID
     */
    public void stopTask(String sessionId) {
        ScheduledFuture<?> future = taskMap.remove(sessionId);
        if (future != null) {
            future.cancel(true);
            log.info("=== 定时任务已停止 === 会话ID: {}", sessionId);
            
            // 如果WebSocket连接仍然存在，发送任务停止的通知
            if (WebSocketServer.isConnected(sessionId)) {
                try {
                    WebSocketServer.sendMessage(sessionId, 
                        "{\"type\":\"taskStopped\",\"message\":\"定时任务已停止\"}");
                } catch (Exception e) {
                    log.error("=== 发送停止通知失败 ===", e);
                }
            }
        }
    }
}



